package cn.myapps.msg.maker;

import cn.myapps.msg.mail.entity.MailTemplate;
import cn.myapps.msg.mail.entity.MsgMail;
import cn.myapps.msg.util.TemplateUtil;
import cn.myapps.msg.vo.MsgCommon;
import cn.myapps.msg.vo.MsgTemplate;
import org.apache.velocity.VelocityContext;


import java.util.List;
import java.util.Map;

/**
 * @Description: E-Mail加工器
 * @Author: nicholas
 * @Date:   2020-06-10
 * @Version: V1.0
 */
public class MailMsgMaker extends BaseMsgMaker implements IMsgMaker {

    public String mailTitle;
    public String mailCc;
    public String mailContent;
    public String templateId;

    /**
     * 准备基础字段
     */
    @Override
    public void prepare(MsgTemplate template) {
        mailTitle = template.getTitle();
        mailContent = template.getContent();
        templateId = template.getId();

        if (template instanceof MailTemplate) {
            MailTemplate mailTemplate =  (MailTemplate)template;
            mailCc = mailTemplate.getMailCc();
        }
    }

    /**
     * 组织E-Mail消息
     *
     * @param msg 消息信息
     * @return MailMsg
     */
    @Override
    public List<MsgMail> makeMsg(MsgCommon msg) {
        List<MsgMail> rtn = MsgMail.buildList(msg);
        Map<String,Object> msgData = toMsgData(msg);
        
        VelocityContext velocityContext = getVelocityContext(msgData);
        String title = TemplateUtil.evaluate(mailTitle, velocityContext);
        String content = TemplateUtil.evaluate(mailContent, velocityContext);

        for (MsgMail msgMail : rtn) {
            msgMail.setTitle(title);
            msgMail.setContent(content);
            msgMail.setTemplateId(templateId);
            if (mailCc != null) {
                String cc = TemplateUtil.evaluate(mailCc, velocityContext);
                msgMail.setCc(cc);
            }
        }
        
        return rtn;
    }
}
